import { Component, OnInit, ChangeDetectorRef, ViewChild, Inject, forwardRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { path } from '../../../../path.config';
import { masterService } from '../../../../../lib/master.service';
import { AppComponent } from '../../../../app.component';
import { NzModalService } from 'ng-zorro-antd';
import * as moment from 'moment';
@Component({
    selector: 'goods-mark-grid',
    templateUrl: './goods-marklist-grid.component.html',
    styleUrls: ['./goods-marklist-grid.component.css'],
    providers: [forwardRef(() => AppComponent)]
})

export class GoodsMarklistGridComponent implements OnInit {
    @ViewChild('lgModal') public lgModal: ModalDirective;
    // 商品打标获取列表
    public getList = path.goodsManage.markManage.getList;
    // 商品打标列表明细
    public getListItem = path.goodsManage.markManage.getListItem;
    // 清除标签
    public clearItem = path.goodsManage.markManage.clearItem;
    // 删除指定标签（图片标签或者文字标签）
    public deleteItem = path.goodsManage.markManage.deleteItem;

    public labelRows = [];

    // 列表项数组
    public rows: Array<any> = [];
    // 表格数据头部标题
    public columns: Array<any> = [
        { title: '选择' },
        { title: 'WOC码' },
        { title: '商品名称' },
        { title: '最新打标时间' },
        { title: '查看' },
        { title: '清空' }
    ];
    // 当前页码
    public page: any = 1;
    // 一共多少页
    public itemsPerPage: number = 10;
    // 分页最多显示的页数
    public maxSize: number = 5;
    // 总页数计数变化时，事件数等于总页数计数
    public numPages: number = 1;
    // 总共的列表项数
    public totalItems: number = 0;
    // 分页器的文本配置
    public localText = {
        firstBtn: '首页',
        lastBtn: '末页',
        previousBtn: '上一页',
        nextBtn: '下一页'
    }

    public isCheckAll = false;

    public editModel: any = {
        goodsSn: '',
        goodsName: "",
        labelName: "",
        beginTime: 0,
        endTime: 0,
        labelUrl: "",
        labelType: 0
    }

    public searchModel: any = {
        goodsSn: '',
        goodsName: '',
        startTime: '',
        endTime: '',
        pageSize: this.itemsPerPage,
        pageIndex: this.page
    };

    constructor(public _masterService: masterService,
        public cdRef: ChangeDetectorRef,
        private confirmServ: NzModalService,
        @Inject(forwardRef(() => AppComponent)) public app: AppComponent) { }

    ngOnInit() {
        this.onChangeTable();
    }

    // 渲染表格
    onChangeTable = (urlObj?, type?) => {
        // 1为筛选
        if (type == 1 && urlObj) {
            this.searchModel.goodsSn = urlObj.goodsSn;
            this.searchModel.goodsName = urlObj.goodsName;
            this.searchModel.startTime = urlObj.startTime ? moment(urlObj.startTime).format('YYYY-MM-DD HH:mm:ss') : '';
            this.searchModel.endTime = urlObj.endTime ? moment(urlObj.endTime).format('YYYY-MM-DD HH:mm:ss') : '';
        } else if (urlObj) {
            this.searchModel.pageSize = urlObj.itemsPerPage;
            this.searchModel.pageIndex = urlObj.page;
        }

        this._masterService
            .getData(this.getList, this.searchModel)
            .subscribe(res => {
                if (res.statusCode == 200) {
                    this.rows = res.data.items;
                    this.rows.forEach((row, i) => {
                        row.createTime = row.createTime * 1000;
                    })
                    this.totalItems = res.data.pagination.totalCount;
                    this.itemsPerPage = res.data.pagination.pageSize;
                    this.page = parseInt(res.data.pagination.pageIndex);
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息： ' + res.errorMessage);
                }
            })
    }

    //根据商品编号获取标签信息
    public getLabel(goodsGuid: string) {
        this._masterService
            .getData(this.getListItem, { goodsGuid: goodsGuid })
            .subscribe(res => {
                if (res.statusCode == 200) {
                    this.labelRows = res.data;
                    this.labelRows.forEach((labelRow, i) => {
                        labelRow.beginTime = labelRow.beginTime * 1000;
                        labelRow.endTime = labelRow.endTime * 1000;
                    })
                    // goodsn与guid在数组数据对象中冗余，所以需要进行判断，不然外层的goodsn会报错
                    if (res.data.length > 0) {
                        this.editModel = res.data[0];
                    }
                    this.cdRef.detectChanges();
                    this.lgModal.show();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息： ' + res.errorMessage);
                }
            });
    }

    //清除标签button
    public clearLabel(goodsGuid?: string) {
        this.confirmServ.confirm({
            nzTitle: '是否确认删除？',
            nzOnOk() {
                postClearLabel();
            }
        })
        let postClearLabel = () => {
            if (goodsGuid) {
                this._masterService
                    .postData(this.clearItem + '?goodsGuids=' + goodsGuid)
                    .subscribe(res => {
                        if (res.statusCode == 200) {
                            this.app.toastSuccess('清除成功!');
                            this.lgModal.hide();
                            this.onChangeTable();
                        } else if (res.statusCode == 401) {
                            this.app.logOff();
                        } else {
                            this.app.toastError('错误信息： ' + res.errorMessage);
                        }
                    });
            } else {
                this.app.toastWarning('所选商品没有可显示的标签！')
            }
        }
    }

    //删除指定商品，指定标签
    public deleteLabel(goodsGuid: string, labelId: number) {
        this.confirmServ.confirm({
            nzTitle: '是否确认删除？',
            nzOnOk() {
                postDeleteLabel();
            }
        })
        let postDeleteLabel = () => {
            this._masterService
                .postData(this.deleteItem + '?goodsGuid=' + goodsGuid + '&labelId=' + labelId)
                .subscribe((res) => {
                    if (res.statusCode == 200) {
                        this._masterService
                            .getData(this.getListItem, { goodsGuid: goodsGuid })
                            .subscribe(res => {
                                if (res.statusCode == 200) {
                                    this.labelRows = res.data;
                                    this.labelRows.forEach((labelRow, i) => {
                                        labelRow.beginTime = labelRow.beginTime * 1000;
                                        labelRow.endTime = labelRow.endTime * 1000;
                                    })
                                    this.app.toastSuccess('删除成功！');
                                    this.cdRef.detectChanges();
                                } else {
                                    this.app.toastError('错误信息： ' + res.errorMessage);
                                }
                            })
                    } else if (res.statusCode == 401) {
                        this.app.logOff();
                    } else {
                        this.app.toastError('错误信息： ' + res.errorMessage);
                    }
                });
        }
    }

    // 全选
    checkAll() {
        if (!this.isCheckAll) {
            this.isCheckAll = true;
            for (let i = 0; i < this.rows.length; i++) {
                this.rows[i].isChecked = true;
            }
            return;
        }
        for (let i = 0; i < this.rows.length; i++) {
            this.rows[i].isChecked = false;
        }
        this.isCheckAll = false;
    }

    // 清除所选标签
    clearSelectedLabel(event) {
        this.confirmServ.confirm({
            nzTitle: '是否清除所选标签？',
            nzOnOk() {
                postClearSelectedLabel();
            }
        })
        let postClearSelectedLabel = () => {
            let arr = [];
            let goodsAllGuid = '';
            // 判断是否选中，选中放入数组中
            for (let i = 0; i < this.rows.length; i++) {
                if (this.rows[i].isChecked == true) {
                    arr.push(this.rows[i].goodsGuid);
                }
            }
            // 将数组容器转换为字符串
            goodsAllGuid = arr.join(',');
            if (goodsAllGuid == "") {
                this.app.toastWarning('所选标签为空！');
                return;
            }
            this._masterService
                .postData(this.clearItem + '?goodsGuids=' + goodsAllGuid)
                .subscribe(res => {
                    if (res.statusCode == 200) {
                        this.app.toastSuccess('删除成功！');
                        this.isCheckAll = false;
                        this.onChangeTable();
                    } else if (res.statusCode == 401) {
                        this.app.logOff();
                    } else {
                        this.app.toastError('错误信息： ' + res.errorMessage);
                    }
                })
        }
    }
}
